package com.madixin.madichat.repository

import com.madixin.madichat.data.api.RetrofitClient
import com.madixin.madichat.data.model.ChatSessionResponse
import com.madixin.madichat.data.model.MessageResponse
import com.madixin.madichat.data.model.UpdateSessionRequest
import com.madixin.madichat.model.ChatSession
import com.madixin.madichat.model.Message
import com.madixin.madichat.util.PreferencesManager
import kotlinx.coroutines.flow.first
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.TimeZone
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.json.JSONObject
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader

class ChatSessionRepository(private val preferencesManager: PreferencesManager) {
    
    suspend fun getChatSessions(page: Int = 1, pageSize: Int = 20): Result<List<ChatSession>> {
        return try {
            // 获取用户token（修改为使用UserRepository的getCurrentToken方法）
            val userRepository = UserRepository.getInstance(preferencesManager)
            val token = userRepository.getCurrentToken()
            if (token.isNullOrEmpty()) {
                return Result.failure(Exception("用户未登录"))
            }
            
            // 调用API获取会话列表
            val response = RetrofitClient.apiService.getChatSessions(
                token = "Bearer $token",
                page = page,
                pageSize = pageSize
            )
            
            if (response.success && response.result != null) {
                // 创建日期格式化工具
                val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault())
                val outputFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
                
                // 将API响应转换为应用模型
                val chatSessions = response.result.map { sessionResponse ->
                    // 格式化时间
                    val formattedTime = try {
                        val date = inputFormat.parse(sessionResponse.updateTime)
                        outputFormat.format(date)
                    } catch (e: Exception) {
                        // 如果解析失败，则使用原始时间字符串
                        android.util.Log.e("ChatSessionRepository", "时间格式化失败: ${e.message}")
                        sessionResponse.updateTime
                    }
                    
                    ChatSession(
                        id = sessionResponse.id,
                        title = sessionResponse.title,
                        lastUpdateTime = formattedTime,
                        isPinned = sessionResponse.pinned
                    )
                }
                Result.success(chatSessions)
            } else {
                Result.failure(Exception(response.message.ifEmpty { "获取会话列表失败" }))
            }
        } catch (e: Exception) {
            Result.failure(Exception("网络请求失败: ${e.message}"))
        }
    }
    
    suspend fun getSessionMessages(sessionId: String, page: Int = 0, size: Int = 50): Result<List<Message>> {
        return try {
            // 获取用户token（修改为使用UserRepository的getCurrentToken方法）
            val userRepository = UserRepository.getInstance(preferencesManager)
            val token = userRepository.getCurrentToken()
            if (token.isNullOrEmpty()) {
                return Result.failure(Exception("用户未登录"))
            }
            
            // 调用API获取会话消息
            val response = RetrofitClient.apiService.getSessionMessages(
                token = "Bearer $token",
                sessionId = sessionId,
                page = page,
                size = size
            )
            
            if (response.success && response.result != null) {
                // 将API响应转换为应用模型
                val messages = response.result.map { messageResponse ->
                    // 将UTC时间转换为本地时间的HH:mm格式
                    val timestamp = formatMessageTime(messageResponse.createTime)
                    
                    Message(
                        id = messageResponse.id,
                        content = messageResponse.content,
                        timestamp = timestamp,
                        isUser = messageResponse.role == "user",
                        // 如果消息类型不是text，可以在这里处理图片等其他类型
                        imageUrl = if (messageResponse.type == "image") messageResponse.content else null
                    )
                }
                Result.success(messages)
            } else {
                Result.failure(Exception(response.message.ifEmpty { "获取消息列表失败" }))
            }
        } catch (e: Exception) {
            Result.failure(Exception("网络请求失败: ${e.message}"))
        }
    }
    
    private fun formatMessageTime(utcTimeString: String): String {
        try {
            // 解析UTC时间
            val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault())
            inputFormat.timeZone = TimeZone.getTimeZone("UTC")
            val date = inputFormat.parse(utcTimeString) ?: return ""
            
            // 转换为本地时间的HH:mm格式
            val outputFormat = SimpleDateFormat("HH:mm", Locale.getDefault())
            outputFormat.timeZone = TimeZone.getDefault()
            return outputFormat.format(date)
        } catch (e: Exception) {
            return ""
        }
    }
    
    // 添加到ChatSessionRepository类中
    suspend fun updateSessionTitle(sessionId: String, newTitle: String): Result<Boolean> {
        return try {
            // 获取用户token
            val userRepository = UserRepository.getInstance(preferencesManager)
            val token = userRepository.getCurrentToken()
            if (token.isNullOrEmpty()) {
                return Result.failure(Exception("用户未登录"))
            }
            
            // 调用API更新会话标题
            val response = RetrofitClient.apiService.updateSessionTitle(
                token = "Bearer $token",
                sessionId = sessionId,
                request = UpdateSessionRequest(newTitle)
            )
            
            if (response.success) {
                Result.success(true)
            } else {
                Result.failure(Exception(response.message.ifEmpty { "更新会话标题失败" }))
            }
        } catch (e: Exception) {
            Result.failure(Exception("网络请求失败: ${e.message}"))
        }
    }
    suspend fun deleteSession(sessionId: String): Result<Boolean> {
        return try {
            val userRepository = UserRepository.getInstance(preferencesManager)
            val token = userRepository.getCurrentToken()
            if (token.isNullOrEmpty()) {
                return Result.failure(Exception("用户未登录"))
            }
            
            // 调用API删除会话
            val response = RetrofitClient.apiService.deleteSession(
                token = "Bearer $token",
                sessionId = sessionId
            )
            
            if (response.success) {
                Result.success(true)
            } else {
                Result.failure(Exception(response.message.ifEmpty { "删除会话失败" }))
            }
        } catch (e: Exception) {
            Result.failure(Exception("网络请求失败: ${e.message}"))
        }
    }

    // 添加到ChatSessionRepository类中
    suspend fun sendMessage(
        sessionId: String,
        content: String,
        type: String = "text",
        image: File? = null,
        options: Map<String, Boolean>? = null,
        onThinking: (String) -> Unit,
        onContent: (String) -> Unit,
        onComplete: (String, String, String, String) -> Unit
    ) {
        try {
            val userRepository = UserRepository.getInstance(preferencesManager)
            val token = userRepository.getCurrentToken()
            if (token.isNullOrEmpty()) {
                throw Exception("用户未登录")
            }

            // 准备请求体
            val sessionIdPart = RequestBody.create("text/plain".toMediaTypeOrNull(), sessionId)
            val contentPart = RequestBody.create("text/plain".toMediaTypeOrNull(), content)
            val typePart = RequestBody.create("text/plain".toMediaTypeOrNull(), type)

            // 可选参数
            var imagePart: MultipartBody.Part? = null
            if (image != null && type == "image") {
                val requestFile = RequestBody.create("image/*".toMediaTypeOrNull(), image)
                imagePart = MultipartBody.Part.createFormData("image", image.name, requestFile)
            }

            var optionsPart: RequestBody? = null
            if (options != null) {
                val optionsJson = JSONObject()
                options.forEach { (key, value) -> optionsJson.put(key, value) }
                optionsPart = RequestBody.create("application/json".toMediaTypeOrNull(), optionsJson.toString())
            }

            // 发送请求并获取流式响应
            val response = RetrofitClient.apiService.sendMessage(
                token = "Bearer $token",
                sessionId = sessionIdPart,
                content = contentPart,
                type = typePart,
                image = imagePart,
                options = optionsPart
            )

            // 处理流式响应
            val reader = BufferedReader(InputStreamReader(response.byteStream()))
            var line: String?

            while (reader.readLine().also { line = it } != null) {
                if (line.isNullOrEmpty()) continue

                // 新的格式是 data:{"event":"content","content":"内容"}
                if (line!!.startsWith("data:")) {
                    val jsonData = line!!.substring(5).trim()
                    try {
                        val jsonObject = JSONObject(jsonData)
                        val eventType = jsonObject.optString("event", "")
                        val content = jsonObject.optString("content", "")

                        when (eventType) {
                            "thinking" -> {
                                onThinking(content)
                            }
                            "content" -> {
                                onContent(content)
                            }
                            "done" -> {
                                // done事件可能没有完整的信息，使用默认值
                                val messageId = jsonObject.optString("messageId", "")
                                val sessionId = jsonObject.optString("sessionId", "")
                                val sender = jsonObject.optString("sender", "ai")
                                val modelId = jsonObject.optString("modelId", "")
                                onComplete(messageId, sessionId, sender, modelId)
                            }
                        }
                    } catch (e: Exception) {
                        android.util.Log.e("ChatSessionRepository", "解析流式响应失败: ${e.message}")
                    }
                }
            }
        } catch (e: Exception) {
            throw Exception("发送消息失败: ${e.message}")
        }
    }
}


